package com.weijing.pretty_app.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.FragmentHandleBinding
import com.weijing.pretty_app.dialog.RestDevicesDialog
import com.weijing.pretty_app.dialog.RestShowDialog
import com.weijing.pretty_app.util.BluetoothSocketManager
import com.weijing.pretty_app.util.CoreUtil
import com.weijing.pretty_app.util.HexConverter
import com.weijing.pretty_app.util.HexDataParse
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.LoadingAnimationHelper
import com.weijing.pretty_app.util.SPUtil
import com.weijing.pretty_app.util.ToastUtils

private const val TAG = "HandleFragment"

/**
 * Handle fragment
 */
class HandleFragment : Fragment() {

    private lateinit var binding: FragmentHandleBinding
    private var maxNum = 10
    private var mineNum = -10
    private var snIndexL = 0
    private var topIndexL = 0
    private var bottomIndexL = 0
    private var snIndexR = 0
    private var topIndexR = 0
    private var bottomIndexR = 0

    private val dataListener: (data: ByteArray) -> Unit = { data ->
        val receivedText = HexConverter.byteArrayToHexString(data) // 默认是 ASCII 格式
        Log.d(TAG, "收到蓝牙数据: $receivedText")
        ToastUtils.show(receivedText + "")
        HexDataParse.parseHexString(receivedText) { funcCode, hexData ->
            when (funcCode) {
                KeyUtil.F3 -> {   //最大值和最小值
                    if (hexData.size == 2) {
                        val fangXiang = hexData[0]
                        val flag = hexData[1]
                        when (fangXiang) {
                            "01" -> {
                                if (flag == "01") { //重置成功
                                    LiveEventBus.get<Boolean>(KeyUtil.RESET_DEVICES).post(true)
                                }
                            }

                            "02" -> {
                                if (flag == "01") { //重置成功
                                    LiveEventBus.get<Boolean>(KeyUtil.RESET_DEVICES).post(true)
                                }
                            }
                        }
                    }
                    Log.i(TAG, "功能码 F2 数据：$hexData")
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentHandleBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.handleFragmentEtWenDuL.text =
            if (SPUtil.getString(KeyUtil.HANDLE_HEAD_L).isNullOrEmpty()) "0" else SPUtil.getString(
                KeyUtil.HANDLE_HEAD_L
            )

        binding.handleFragmentEtWenDuR.text =
            if (SPUtil.getString(KeyUtil.HANDLE_HEAD_R).isNullOrEmpty()) "0" else SPUtil.getString(
                KeyUtil.HANDLE_HEAD_R
            )

        setTouchFeedback(binding.handleFragmentClJianL, binding.handleFragmentClJianCircleL)
        setTouchFeedback(binding.handleFragmentClJiaL, binding.handleFragmentClJiaCircleL)

        setTouchFeedback(binding.handleFragmentClJianR, binding.handleFragmentClJianCircleR)
        setTouchFeedback(binding.handleFragmentClJiaR, binding.handleFragmentClJiaCircleR)

        binding.handleFragmentClJianL.setOnClickListener {
            val wenDu = binding.handleFragmentEtWenDuL.text.toString()
            var wenDuInt = wenDu.toInt()
            if (wenDuInt <= mineNum) {
                return@setOnClickListener
            }
            wenDuInt -= 1
            binding.handleFragmentEtWenDuL.setText(wenDuInt.toString())
        }

        binding.handleFragmentClJiaL.setOnClickListener {
            val wenDu = binding.handleFragmentEtWenDuL.text.toString()
            var wenDuInt = wenDu.toInt()
            if (wenDuInt >= maxNum) {
                return@setOnClickListener
            }
            wenDuInt += 1
            binding.handleFragmentEtWenDuL.setText(wenDuInt.toString())
        }

        binding.handleFragmentClJianR.setOnClickListener {
            val wenDu = binding.handleFragmentEtWenDuR.text.toString()
            var wenDuInt = wenDu.toInt()
            if (wenDuInt <= mineNum) {
                return@setOnClickListener
            }
            wenDuInt -= 1
            binding.handleFragmentEtWenDuR.setText(wenDuInt.toString())
        }

        binding.handleFragmentClJiaR.setOnClickListener {
            val wenDu = binding.handleFragmentEtWenDuR.text.toString()
            var wenDuInt = wenDu.toInt()
            if (wenDuInt >= maxNum) {
                return@setOnClickListener
            }
            wenDuInt += 1
            binding.handleFragmentEtWenDuR.setText(wenDuInt.toString())
        }

        //保存L
        binding.handleFragmentClLSave.setOnClickListener {
            SPUtil.put(KeyUtil.HANDLE_HEAD_L, binding.handleFragmentEtWenDuL.text.toString())
            CoreUtil.showTvCustomToast(binding.handleFragmentTvOkL)

            sendData("L", binding.handleFragmentEtWenDuL.text.toString().toInt())
        }
        //保存R
        binding.handleFragmentClRSave.setOnClickListener {
            SPUtil.put(KeyUtil.HANDLE_HEAD_R, binding.handleFragmentEtWenDuR.text.toString())
            CoreUtil.showTvCustomToast(binding.handleFragmentTvOkR)
            sendData("R", binding.handleFragmentEtWenDuR.text.toString().toInt())
        }

        binding.handleTvSnL.setOnClickListener {
            snIndexL += 1
        }

        binding.handleTvLTopReset.setOnClickListener {
            if (snIndexL < 3) {
                return@setOnClickListener
            }
            topIndexL += 1
        }

        binding.handleTvLBottomReset.setOnClickListener {
            if (topIndexL < 1) {
                return@setOnClickListener
            }
            bottomIndexL += 1

            RestShowDialog().showing(childFragmentManager, "L",
                object : RestDevicesDialog.SetRestClickListener {
                    override fun onClickListener() {
                        sendRestData("L")
                    }
                })
        }

        binding.handleTvSnR.setOnClickListener {
            snIndexR += 1
        }

        binding.handleTvRTopReset.setOnClickListener {
            if (snIndexR < 3) {
                return@setOnClickListener
            }
            topIndexR += 1
        }

        binding.handleTvRBottomReset.setOnClickListener {
            if (topIndexR < 1) {
                return@setOnClickListener
            }
            bottomIndexR += 1

//            ToastUtils.show("R重置成功")
//            sendRestData("R")

            RestShowDialog().showing(childFragmentManager, "R",
                object : RestDevicesDialog.SetRestClickListener {
                    override fun onClickListener() {
                        sendRestData("R")
                    }
                })
        }

        getSpData()
    }

    private fun getSpData() {
        SPUtil.getString(KeyUtil.LEFT_HANDLE_SN)?.let {
            binding.handleTvSnL.text = it
        }
        SPUtil.getString(KeyUtil.RIGHT_HANDLE_SN)?.let {
            binding.handleTvSnR.text = it
        }

        SPUtil.getString(KeyUtil.WAVE_LENGTH_L)?.let {
            binding.handleTvWaveL.text = it
        }
        SPUtil.getString(KeyUtil.WAVE_LENGTH_R)?.let {
            binding.handleTvWaveR.text = it
        }

        SPUtil.getString(KeyUtil.POWER_VALUE_L)?.let {
            binding.handleTvPowerL.text = it
        }
        SPUtil.getString(KeyUtil.POWER_VALUE_R)?.let {
            binding.handleTvPowerR.text = it
        }
    }

    private fun setTouchFeedback(touchTarget: View, backgroundTarget: View) {
        touchTarget.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    backgroundTarget.setBackgroundResource(R.drawable.button_click)
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    backgroundTarget.setBackgroundResource(R.drawable.shape_circle_00c1cd)
                }
            }
            false
        }
    }

    /**
     * @param num 温度
     */
    private fun sendData(fangXiang: String, num: Int) {
        var mFangXiang = ""
        when (fangXiang) {
            "L" -> {
                mFangXiang = "01 "
            }

            "R" -> {
                mFangXiang = "02 "
            }
        }
        val data3 = HexConverter.intTo1ByteHex(num)
        val value3Hex = data3.joinToString(" ") { "%02X".format(it) }
        val commandAll = KeyUtil.SETTING_HANDLE_WENDU_COMMAND + mFangXiang + value3Hex + KeyUtil.EE
        val data = HexConverter.hexStringToByteArray(commandAll)
        Log.i(TAG, "设置页面保存手柄温度-- $commandAll")
        BluetoothSocketManager.send(data)
    }

    //恢复出厂设置
    private fun sendRestData(fangXiang: String) {
        var mFangXiang = ""
        when (fangXiang) {
            "L" -> {
                mFangXiang = "01 "
            }

            "R" -> {
                mFangXiang = "02 "
            }
        }

        val commandAll = KeyUtil.REST_DEVICES + mFangXiang + "01" + KeyUtil.EE
        val data = HexConverter.hexStringToByteArray(commandAll)
        Log.i(TAG, "恢复出厂设置-- $commandAll")
        BluetoothSocketManager.send(data)
    }

    private fun clearResetIndexL() {
        snIndexL = 0
        topIndexL = 0
        bottomIndexL = 0
    }

    private fun clearResetIndexR() {
        snIndexR = 0
        topIndexR = 0
        bottomIndexR = 0
    }

    override fun onResume() {
        super.onResume()
        BluetoothSocketManager.addDataReceivedListener(dataListener)
        Log.i(TAG, "onResume: ")
        val lCount =
            if (SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_L) == null) 0 else SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_L)!!
        val rCount =
            if (SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_R) == null) 0 else SPUtil.getInt(KeyUtil.HANDLE_SEND_COUNT_ALL_R)!!
        binding.handleFragmentEtIndexL.setText(lCount.toString())
        binding.handleFragmentEtIndexR.setText(rCount.toString())

        if (lCount >= KeyUtil.MAX_COUNT) {
            binding.handleTvEndLifeL.visibility = View.VISIBLE
        }
        if (rCount >= KeyUtil.MAX_COUNT) {
            binding.handleTvEndLifeR.visibility = View.VISIBLE
        }
    }

    override fun onPause() {
        super.onPause()
        clearResetIndexL()
        clearResetIndexR()
    }

    override fun onStop() {
        super.onStop()
        clearResetIndexL()
        clearResetIndexR()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 避免内存泄漏或多次回调
        BluetoothSocketManager.removeDataReceivedListener(dataListener)
    }
}